<template>
  <el-main style="padding:0px; background-color: rgb(230,241,255);">
    <el-container>
      <el-header height="48px;" class="text-right">
        <button class="btn-user btn-user1" @click="openPort(0)">
          <span class="imguser imguser1"></span>
          {{ $t('Verification')}}
        </button>
        <button class="btn-user btn-user2" @click="openPort(1)">
          <span class="imguser imguser2"></span>
          {{$t('download')}}
        </button>
        <button class="btn-user btn-user3" @click="openWin">
          <span class="imguser imguser3"></span>
          {{$t('串口监视器')}}
        </button>
        &nbsp;&nbsp;
        <img
          src="@/assets/images/恢复.png"
          onclick="Blockly.mainWorkspace.undo(1)"
          :title="$t('recovery')"
          class="float-right revoke"
          height="30"
          :alt="$t('recovery')"
          srcset
        />
        <img
          src="@/assets/images/撤销.png"
          onclick="Blockly.mainWorkspace.undo(0)"
          :title="$t('Revoke')"
          class="float-right revoke"
          height="30"
          :alt="$t('Revoke')"
          srcset
        />
      </el-header>
      <el-main style="padding:0px;">
        <div id="blocklyDiv"></div>
      </el-main>
    </el-container>
    <button class="position-fixed" type="button" id="codebutton" @click="openCode">
      <i :class="icon"></i>
    </button>
    <transition name="el-zoom-in-center">
      <el-container id="rightCode" v-show="code" class="position-fixed">
        <div
          class="el-aside"
          id="rightBorderLeft"
          width="3px"
          v-on="{ mousedown: movey, mouseup: mouseupy }"
        ></div>
        <el-container style="background:#00979d;">
          <el-main id="code_size"></el-main>
          <!-- <div id="rightBorderRight" v-on="{ mousedown: moveX, mouseup: mouseupX }"></div> -->
          <el-footer height="300px" style="padding:0px;" id="logText">
            <textarea name readonly id="arduinoLog"></textarea>
          </el-footer>
        </el-container>
      </el-container>
    </transition>
    <el-dialog :title="$t('请选择串口')" :visible.sync="port" width="30%" :before-close="portfalse">
      <div
        class="form-check btn btn-lg btn-block"
        v-for="(v, i) in portlist"
        v-bind:class="{
          'btn-primary': v.comName == clickport,
          'btn-secondary': v.comName != clickport
        }"
        @click="
          clickport = v.comName;
          btnBlock = i;
        "
        :key="i"
      >
        <input class="form-check-input" type="radio" v-model="clickport" :value="v.comName" checked />
        <label class="form-check-label bigshotradio" v-text="v.comName"></label>
        <i class="el-icon-success" v-show="v.comName == clickport"></i>
      </div>
      <div class="text-center text-danger" v-show="!portlist.length">
        <i class="el-icon-warning"></i>
        {{$t('没有找到串口')}}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="portfalse">{{$t('Close')}}</el-button>
        <el-button type="primary" @click="portClose">{{$t('Confirm')}}</el-button>
      </span>
    </el-dialog>
  </el-main>
</template>

<script>
const Blockly = window.Blockly;
const ace = window.ace;
import Ele, { changeDivHeight } from "../../render/index.js";
import { mediapath } from "../../render/mian.js";
import local from "../../plugins/local.js";
import { accessSync, constants } from "fs";
import { ipcRenderer } from "electron";
window.onresize = function() {
  changeDivHeight();
};
export default {
  name: "bigShot",
  data() {
    return {
      code: false,
      log: false,
      port: false,
      disX: 500,
      btnBlock: null,
      portlist: [],
      clickport: null,
      icon: "el-icon-arrow-left",
      state: {},
      savePort: null
    };
  },
  props: ["arduino", "ropenXml"],
  async mounted() {
    this.state = {};
    changeDivHeight();
    this.init();
    const result =
      '<xml xmlns="http://www.w3.org/1999/xhtml"><block type="base_setup" id="lw^YX2*Pn.]Jce-ij-L-" x="236" y="149"></block></xml>';
    let xml = Blockly.Xml.textToDom(result);
    
    const x = process.argv[process.argv.length - 1];
    try {
      if (process.env.NODE_ENV !== "development") {
        accessSync(x, constants.R_OK);
        this.ropenXml(x);
        process.argv[process.argv.length - 1] = "";
      }
      Blockly.Xml.appendDomToWorkspace(xml, Blockly.mainWorkspace);
    } catch (err) {
      console.log(err)
      Blockly.Xml.appendDomToWorkspace(xml, Blockly.mainWorkspace);
    }
  },
  watch: {
    code(v) {
      if (v) {
        setTimeout(() => {
          document.getElementById("codebutton").style.right =
            document.getElementById("rightCode").offsetWidth + "px";
          this.icon = "el-icon-arrow-right";
        }, 200);
      } else {
        document.getElementById("codebutton").style.right = 0;
        this.icon = "el-icon-arrow-left";
      }
    }
  },
  methods: {
    openWin() {
      ipcRenderer.send("openPortWin");
    },
    init() {
      const blocklyDiv = document.getElementById("blocklyDiv");
      const toolbox = document.getElementById("toolbox");
      const locale = this.$i18n.locale;
      if (locale === "en") {
        for(const v of toolbox.children){
          v.attributes.name.value = local[v.attributes.name.value];
        }
      }
      const obj = Object.assign(
        {},
        {
          css: true,
          media: mediapath,
          toolbox,
          zoom: {
            controls: true,
            wheel: true,
            startScale: 0.675
          },
          grid: {
            spacing: 40,
            length: 2,
            colour: "#ddd"
          },
          colours: {
            workspace: "#F9F9F9",
            flyout: "#F9F9F9",
            toolbox: "#FFFFFF",
            toolboxSelected: "#E9EEF2",
            scrollbar: "#CECDCE",
            scrollbarHover: "#CECDCE",
            insertionMarker: "#000000",
            insertionMarkerOpacity: 0.2,
            fieldShadow: "rgba(255, 255, 255, 0.3)",
            dragShadowOpacity: 0.6
          },
          trashcan: false
        }
      );
      const workspace = Blockly.inject(blocklyDiv, obj);
      window.workspace = workspace;
      Blockly.svgResize(workspace);
      let editorSideCode = ace.edit("code_size");
      editorSideCode.setTheme("ace/theme/xcode");
      editorSideCode.getSession().setMode("ace/mode/c_cpp");
      editorSideCode.setFontSize(17);
      editorSideCode.setShowPrintMargin(false);
      editorSideCode.setReadOnly(true);
      editorSideCode.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true
      });

      function myUpdateFunction(event) {
        if (event.type == Blockly.Events.UI) return; // Don't update UI events.
        let inocold = Blockly.Arduino.workspaceToCode(Blockly.mainWorkspace);
        editorSideCode.setValue(inocold, -1);
      }
      workspace.addChangeListener(myUpdateFunction);
      //load from url parameter (single param)
      //http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript
      for (let x of document.getElementsByClassName("blocklyTreeLabel")) {
        x.style = "";
      }

      this.state.workspace = workspace;
    },
    openCodeTrue() {
      this.code = true;
    },
    openCode() {
      this.code = !this.code;
    },
    portClose() {
      if (!this.clickport) {
        this.$message(this.$t("请选择串口"));
        return;
      }
      this.port = false;
      this.save1(this.clickport);
      this.cupload(1);
    },
    save1(i) {
      this.savePort = i;
    },
    async openPort(i) {
      if (i === 0) {
        this.cupload(0);
      } else {
        this.clickport = null;
        this.portlist = [];
        let list = await Ele.getport();
        for (let v of list) {
          let productId = parseInt(v.productId, 16);
          let vendorId = parseInt(v.vendorId, 16);
          if (productId === 29987 && vendorId === 6790) {
            this.portlist.push(v);
          }
        }
        this.port = true;
      }
    },
    async portfalse() {
      this.port = false;
    },
    movey(event) {
      this.disX = event.clientX;
      const rightcode = document.getElementById("rightCode");
      this.offwidth = rightcode.offsetWidth;
      document.addEventListener("mousemove", this.movemovuey, false);
    },
    mouseupy() {
      document.removeEventListener("mousemove", this.movemovuey);
    },
    movemovuey(event) {
      let y = this.disX - event.clientX + this.offwidth;
      document.getElementById("rightCode").style.width = y + "px";
      document.getElementById("codebutton").style.right =
        document.getElementById("rightCode").offsetWidth + "px";
    },
    moveX(event) {
      this.disY = event.clientY;
      this.codesizeh = document.getElementById("code_size").style.height;
      document.addEventListener("mousemove", this.movemovueX, false);
    },
    mouseupX() {
      document.removeEventListener("mousemove", this.movemovueX);
    },
    movemovueX(event) {
      const rightcode = document.getElementById("rightCode");
      let offheight = parseInt(rightcode.style.height);
      let y = this.disY - event.clientY;
      let a = document.getElementById("code_size");
      let b = document.getElementById("logText");
      a.style.height = parseInt(this.codesizeh) - y + "px";
      b.style.height = offheight - parseInt(this.codesizeh) + y - 3 + "px";
    },
    async cupload(i) {
      let inspec = Ele.inspectxml(this);
      if (inspec.state != 0) {
        this.$notify({
          title: this.$t("warning"),
          message: inspec.err,
          type: "warning"
        });
        return;
      }
      this.code = true;
      const loading = this.$loading({
        lock: true,
        text: this.$t("Loading"),
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      this.$emit("openCodeTrue");
      let ele = new Ele({ COMV: this.savePort });
      let x;
      let text;
      try {
        x = await ele.cupload(i, this);
      } catch (err) {
        x = false;
        text = err;
      }
      loading.close();
      this.open(x, i, text);
    },
    open(x, i, text = "") {
      let text1;
      let title;
      let text2;
      title = this.$t("Tips");

      if (i) {
        text1 = this.$t("download");
      } else {
        text1 = this.$t("Verification");
      }
      if (x) {
        text2 = this.$t("Success");
      } else {
        text2 = this.$t("fail");
      }
      this.$alert(`${text1}${text2} ${text} `, title, {
        confirmButtonText: this.$t("Determine")
      });
    }
  }
};
</script>

<style>
.btnx {
  display: inline-block;
  height: 32px;
  border: 1px solid hsla(0, 0%, 0%, 0.15);
  cursor: pointer;
  background-color: #d9e4f3;
}
.btnx:hover {
  background-color: hsla(215, 100%, 95%, 1);
}

.btn-user {
  background-color: #6fb9fe;
  color: #ffffff;
  height: 32px;
  font-size: 0.8rem;
  padding: 0.125rem 1.25rem 0;
  border-radius: 1rem 1rem 1rem 1rem;
  margin-top: 3px;
}

.btn-user .imguser {
  width: 0.8rem;
  height: 0.8rem;
  display: inline-block;
  background-repeat: no-repeat;
  background-size: cover;
}

.btn-user:hover {
  color: #6fb9fe;
  background-color: #ffffff;
}

.el-icon-success {
  display: inline-block;
  text-align: right;
}
.revoke {
  margin-top: 8px;
  margin-left: 5px;
  margin-right: 5px;
}
#codebutton {
  top: 45%;
  right: 0;
  height: 100px;
  width: 30px;
  cursor: pointer;
  color: #fff;
  font-size: 25px;
  border-top-left-radius: 100px;
  border-bottom-left-radius: 100px;
  z-index: 95;
  padding: 0;
  margin: 0;
  background: grey;
  box-shadow: none !important;
  transition: right 0.5s;
}
#codebutton:hover {
  background-color: rebeccapurple;
}
.bigshotradio {
  margin-left: 50px;
}

#rightCode {
  width: 500px;
  right: 0;
  top: 86px;
}
#rightBorderLeft {
  width: 3px;
  cursor: w-resize;
  background-color: rgba(37, 37, 37, 1);
  z-index: 10;
}
#rightBorderRight {
  width: 100%;
  height: 3px;
  cursor: s-resize;
  background-color: rgba(37, 37, 37, 1);
}

#logText {
  background-color: #ffffff;
}
.rightcon {
  height: 100%;
  width: 497px;
}
.img-f {
  top: 60px;
  left: 0px;
  z-index: 100;
  height: 62px;
  padding: 1px;
  background: rgb(255, 224, 99);
}
#arduinoLog {
  width: 100%;
  height: 100%;
  overflow: scroll;
  font-size: 12px;
  background-color: #000000;
  color: #fff;
  word-wrap: break-word;
  word-break: break-all;
}
</style>
